package jinyilw.swing.rlaf.ui;

import jinyilw.swing.ColorTools;
import jinyilw.swing.FontTools;
import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.JComponent;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicListUI;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;

/**
 * @author Jinyi
 */
public class RListUI extends BasicListUI
{
	ListCellRenderer renderer;
	boolean isFileList, isLeftToRight;

	public static ComponentUI createUI(JComponent c)
	{
		return new RListUI();
	}

	@Override
	public void installUI(JComponent c)
	{
		super.installUI(c);
		c.setOpaque(false);
		c.setBackground(ColorTools.transparentColor);
		isLeftToRight = list.getComponentOrientation().isLeftToRight();
		if (list.getCellRenderer() == null)
			list.setCellRenderer(new RListRenderer());
		list.setFont(FontTools.defaultFont);
	}

	@Override
	public void update(Graphics g, JComponent c)
	{
		if (renderer == null)
		{
			isFileList = Boolean.TRUE
					.equals(list.getClientProperty("List.isFileList"));
			renderer = list.getCellRenderer();
			// System.out.println(renderer);
			if (renderer instanceof JComponent)
				((JComponent) renderer).setOpaque(false);
		}
		if (isFileList)
		{
			g.setColor(RThemeColor.colorSet.transTBGColor);
			g.fillRect(0, 0, c.getWidth(), c.getHeight());
		}
		c.setForeground(RThemeColor.colorSet.textColor);
		paint(g, c);
	}

	@Override
	protected void paintCell(Graphics g, int row, Rectangle rowBounds,
			ListCellRenderer cellRenderer, ListModel dataModel,
			ListSelectionModel selModel, int leadIndex)
	{
		Object value = dataModel.getElementAt(row);
		boolean cellHasFocus = list.hasFocus() && (row == leadIndex);
		boolean isSelected = selModel.isSelectedIndex(row);
		Component rendererComponent = cellRenderer.getListCellRendererComponent(
				list, value, row, isSelected, cellHasFocus);
		int cx = rowBounds.x;
		int cy = rowBounds.y;
		int cw = rowBounds.width;
		int ch = rowBounds.height;
		if (isFileList)
		{
			int w = Math.min(cw,
					rendererComponent.getPreferredSize().width + 4);
			if (!isLeftToRight)
				cx += (cw - w);
			cw = w;
		}
		rendererPane.paintComponent(g, rendererComponent, null, cx, cy, cw, ch,
				true);
	}
}
